<template>
    <div class="ups">
        <div v-for="(item,index) in fileurls" :key="item" class="fileDiv">
            <img v-if="item.fileUrl && item.isImg" :src="item.fileUrl" class="avatar" />
            <span v-if="item.fileUrl && !item.isImg" class="avatar-uploader-file"><span>{{item.name}}</span></span>
            <span v-if="!item.fileUrl" class="up_uploading">上传中...</span>
            <span class="up_del" v-show="item.fileUrl" @click="del(index)"></span>
            <div class="progress" v-show="item.progressFlag">
                <span><u :style="'width:'+item.loadProgress"></u></span>
                <i>{{item.loadProgress}}</i>
            </div>
        </div>
        <div class="upDiv">
            <span class="avatar-uploader"></span>
            <input type="file" :accept="accept" multiple="multiple" @change="upfile" />
        </div>
    </div>
</template>

<script setup>
import { ref,reactive,getCurrentInstance,toRefs,toRaw,computed, pushScopeId,watch } from 'vue'
let { proxy } = getCurrentInstance()
const emit = defineEmits(['update:files']) //此处要完全对应，采用固定的update:prop属性
const imgTypes = ['jpg','jpeg','png','gif']
let isUpload = false //默认没上传过

const props = defineProps({
    accept: { type: Array, default: ['image/jpeg','image/png','image/gif'] }, //'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    debug: { type: Boolean, default: false },
    old_files: { type: String, default: "", require: true },
    files: { type: String, default: "", require: true },
    dir: { type: String, default: "" },
    maxlength: { type: Number, default: 0 }, //默认0，不限制
    maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
    maxwidth: { type: Number, default: 0 },
    maxheight: { type: Number, default: 0 },
    background: { type: String, default: "" },
})
let init = val => {
    return val.split(",").filter(t => t!="").map(t => {
        let tmp = {
            id: Math.random(),
            name: t,
            progressFlag: false,
            loadProgress: "0%",
            fileUrl: "",
            isImg: t=="" ? "" : imgTypes.some(p => p === t.split('.').pop().toLowerCase())
        }
        tmp.fileUrl = `${proxy.$setting.globalUrl.fileurl}/${props.dir}/${t}`
        // if (!isUpload && t != "")
        //     tmp.fileUrl = `${proxy.$setting.globalUrl.fileurl}/${props.dir}/${t}`
        // if (isUpload && t != "")
        //     tmp.fileUrl = `${proxy.$setting.globalUrl.upload}/${t}`
        return tmp
    })
}
let obj = reactive({
    innerFiles: props.files.split(",").filter(t => t!=""),
    fileurls: init(props.files),
})
watch(
    () => props.old_files,
    (val) => {
        obj.innerFiles = val.split(",").filter(t => t!="")
        obj.fileurls = init(val)
    },
    // { immediate: true, deep: true } //immediate表示第一次就输出，默认是false；deep表示深度监听，能监听到对像的内容变化
)

let del = i => {
    obj.innerFiles.splice(i,1)
    obj.fileurls.splice(i,1)
    emit('update:files', obj.innerFiles.join())
    // emit('update:files', obj.fileurls.map(t => t.name))
}
let upfile = e => {
    let files = []
    for(let i=0; i<e.srcElement.files.length; i++)
        files.push(e.srcElement.files[i])
    // console.log(files)
    files.forEach(file => {
        if (props.debug) console.log(file.type)
        let isType = props.accept.some(t => t === file.type)
        let isLimit = file.size < props.maxsize

        if (!isType) {
            proxy.elMessageMixin(`${file.type}格式不正确`, 'error')
            return
        }
        if (!isLimit) {
            proxy.elMessageMixin(`${file.name}超过${props.maxsize/file.size}M`, 'error')
            return
        }

        //检查完成，可以上传
        const curItem = Math.random()
        let upItem = {
            id: curItem,
            name: file.name,
            progressFlag: true,
            loadProgress: "0%",
            // fileUrl: "", //不给，到完成再给，这样上面就能判断了
            isImg: imgTypes.some(p => p === file.name.split('.').pop().toLowerCase())
        }
        console.log(upItem);
        obj.fileurls.push(upItem) //加到前面
        let formData = new FormData(); //这样可以给form参数了
        formData.append("type", file.type);
        formData.append("file", file);
        if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
        if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
        if (props.background != "") formData.append("background", props.background);

        proxy.$ajax({
            baseURL: "",
            url: proxy.$setting.globalUrl.uploadserver,
            data: formData,
            isUploadFile: true,
            bfLoading: false,
            timeout: 0,
            progress: p => {
                obj.fileurls.find(t => t.id==curItem).loadProgress = (p.loaded / p.total * 100 | 0) + '%' //这里不能直接用upItem，因为实际上这时还没绑上去，即指向还未生效
            }
        }).then(res => {
            upItem.fileUrl = `${proxy.$setting.globalUrl.upload}/${res.filename}`
            upItem.name = res.filename
            obj.innerFiles.push(res.filename)
            // emit('update:files', obj.fileurls.map(t => t.name))
            emit('update:files', obj.innerFiles.join())
            upItem.progressFlag = false
        }).catch((() => {
            upItem.progressFlag = false
            // obj.fileurls.remove(upItem) //删掉之前加的
        }))
    });
}

let { fileurls } = toRefs(obj)
</script>

<style lang="scss" scoped>
    $w: 120px;
    $h: 120px;
    $color: #d8dae2;
    .ups { display: flex; flex-wrap: wrap; }
    .fileDiv { margin-right: 5px; position: relative; }
    .upDiv { position: relative; width: $w; height: $h+20; overflow: hidden; }
    .up_del { position: absolute; top: 0; right: 6px; }
    .up_del::after { content: "\e74b"; font-family: "iconfont"; font-size: 10px; }
    .upDiv input { position: absolute; top:-20px; font-size:0; -webkit-appearance:none; width: $w; height: $h+20; }
    .avatar { width: $w; height: $h; object-fit: contain; box-sizing: border-box; border: 1px solid $color; }
    .avatar-uploader-file::after { content:'\e6b7'; font-family: "iconfont"; font-size: 40px; }
    .avatar-uploader-file span { position: absolute; bottom: 0; font-size: 12px; }
    .avatar-uploader,.avatar-uploader-file, .up_uploading { position: relative; width: $w; height: $h; overflow: hidden; background-color: #FFF; border: 1px solid $color; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }
    .avatar-uploader::after { content:'\e626'; font-family: "iconfont"; font-size: 40px; color: $color; }
    .up_uploading { font-size:12px; }
    .progress { display: flex; width:120px; margin-top: 3px; align-items: center; }
    .progress * { display: flex; font-style: normal; font-size: 12px; }
    .progress span { flex: 1; align-items: center; height:6px; border-radius: 3px; background-color: $color; margin-right: 5px; }
    .progress u { background-color: #3a4fbd; height:6px; border-radius: 3px;  }
</style>